package com.study.ws.util.ws;

import org.springframework.util.ObjectUtils;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

/**
 * @author xl-9527
 * @since 2025/3/27
 **/
public class WsUtil {

    public static int getUserIdByWebSocketSession(final WebSocketSession webSocketSession) {
        Object userId = webSocketSession.getAttributes().get("userId");
        if (ObjectUtils.isEmpty(userId)) {
            try {
                webSocketSession.sendMessage(new TextMessage("userId not found"));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            throw new RuntimeException("userId not found");
        }
        return Integer.parseInt(String.valueOf(userId));
    }
}
